import 'package:flutter/material.dart';
import 'package:mathfun/utils/responsive_util.dart';
import 'package:shared_preferences/shared_preferences.dart';

class SettingsPage extends StatefulWidget {
  @override
  _SettingsPageState createState() => _SettingsPageState();
}

class _SettingsPageState extends State<SettingsPage> {
  // 默认设置值
  int dotTrainingQuestions = 10;
  int audioTrainingQuestions = 10;
  String audioTrainingDifficulty = '10以内加减法';
  int audioQuestionDuration = 3;
  int dotFlashTrainingQuestions = 10;
  int dotFlashDisplayDuration = 2;
  int dotFlashMinDots = 8;
  int dotFlashMaxDots = 12;

  // 难度选项列表
  final List<String> difficultyOptions = [
    '10以内加减法',
    '20以内加减法',
    '20以内连加连减',
    '50以内连加连减',
    '表内乘法',
  ];

  @override
  void initState() {
    super.initState();
    _loadSettings();
  }

  // 加载保存的设置
  Future<void> _loadSettings() async {
    final prefs = await SharedPreferences.getInstance();
    setState(() {
      dotTrainingQuestions = prefs.getInt('dotTrainingQuestions') ?? 10;
      audioTrainingQuestions = prefs.getInt('audioTrainingQuestions') ?? 10;
      audioTrainingDifficulty =
          prefs.getString('audioTrainingDifficulty') ?? '10以内加减法';
      audioQuestionDuration = prefs.getInt('audioQuestionDuration') ?? 3;
      dotFlashTrainingQuestions = prefs.getInt('dotFlashTrainingQuestions') ?? 10;
      dotFlashDisplayDuration = prefs.getInt('dotFlashDisplayDuration') ?? 2;
      dotFlashMinDots = prefs.getInt('dotFlashMinDots') ?? 8;
      dotFlashMaxDots = prefs.getInt('dotFlashMaxDots') ?? 12;
    });
  }

  // 保存设置
  Future<void> _saveSettings() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setInt('dotTrainingQuestions', dotTrainingQuestions);
    await prefs.setInt('audioTrainingQuestions', audioTrainingQuestions);
    await prefs.setString('audioTrainingDifficulty', audioTrainingDifficulty);
    await prefs.setInt('audioQuestionDuration', audioQuestionDuration);
    await prefs.setInt('dotFlashTrainingQuestions', dotFlashTrainingQuestions);
    await prefs.setInt('dotFlashDisplayDuration', dotFlashDisplayDuration);
    await prefs.setInt('dotFlashMinDots', dotFlashMinDots);
    await prefs.setInt('dotFlashMaxDots', dotFlashMaxDots);

    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text('设置已保存')),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('训练设置')),
      body: SingleChildScrollView(
        child: Padding(
          padding: EdgeInsets.all(16.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              _buildSectionTitle('点数识别训练设置'),
              _buildSettingCard(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text('每次训练题量', style: TextStyle(fontSize: 16)),
                    SizedBox(height: 8),
                    Slider(
                      value: dotTrainingQuestions.toDouble(),
                      min: 5,
                      max: 30,
                      divisions: 25,
                      label: dotTrainingQuestions.toString(),
                      onChanged: (value) {
                        setState(() {
                          dotTrainingQuestions = value.toInt();
                        });
                      },
                    ),
                    Text('$dotTrainingQuestions 题',
                        style: TextStyle(color: Colors.grey[600])),
                  ],
                ),
              ),
              SizedBox(height: 24),
              _buildSectionTitle('听算训练设置'),
              _buildSettingCard(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text('每次训练题量', style: TextStyle(fontSize: 16)),
                    SizedBox(height: 8),
                    Slider(
                      value: audioTrainingQuestions.toDouble(),
                      min: 5,
                      max: 30,
                      divisions: 25,
                      label: audioTrainingQuestions.toString(),
                      onChanged: (value) {
                        setState(() {
                          audioTrainingQuestions = value.toInt();
                        });
                      },
                    ),
                    Text('$audioTrainingQuestions 题',
                        style: TextStyle(color: Colors.grey[600])),
                    SizedBox(height: 16),
                    Text('训练难度', style: TextStyle(fontSize: 16)),
                    SizedBox(height: 8),
                    DropdownButtonFormField<String>(
                      value: audioTrainingDifficulty,
                      decoration: InputDecoration(
                        border: OutlineInputBorder(),
                        contentPadding:
                            EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                      ),
                      items: difficultyOptions.map((String difficulty) {
                        return DropdownMenuItem<String>(
                          value: difficulty,
                          child: Text(difficulty),
                        );
                      }).toList(),
                      onChanged: (String? newValue) {
                        if (newValue != null) {
                          setState(() {
                            audioTrainingDifficulty = newValue;
                          });
                        }
                      },
                    ),
                    SizedBox(height: 16),
                    Text('听题时长（秒）', style: TextStyle(fontSize: 16)),
                    SizedBox(height: 8),
                    Slider(
                      value: audioQuestionDuration.toDouble(),
                      min: 1,
                      max: 10,
                      divisions: 9,
                      label: audioQuestionDuration.toString(),
                      onChanged: (value) {
                        setState(() {
                          audioQuestionDuration = value.toInt();
                        });
                      },
                    ),
                    Text('$audioQuestionDuration 秒',
                        style: TextStyle(color: Colors.grey[600])),
                  ],
                ),
              ),
              SizedBox(height: 24),
              _buildSectionTitle('数点快闪训练设置'),
              _buildSettingCard(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text('每次训练题量', style: TextStyle(fontSize: 16)),
                    SizedBox(height: 8),
                    Slider(
                      value: dotFlashTrainingQuestions.toDouble(),
                      min: 5,
                      max: 30,
                      divisions: 25,
                      label: dotFlashTrainingQuestions.toString(),
                      onChanged: (value) {
                        setState(() {
                          dotFlashTrainingQuestions = value.toInt();
                        });
                      },
                    ),
                    Text('$dotFlashTrainingQuestions 题',
                        style: TextStyle(color: Colors.grey[600])),
                    SizedBox(height: 16),
                    Text('闪现时长（秒）', style: TextStyle(fontSize: 16)),
                    SizedBox(height: 8),
                    Slider(
                      value: dotFlashDisplayDuration.toDouble(),
                      min: 1,
                      max: 5,
                      divisions: 4,
                      label: dotFlashDisplayDuration.toString(),
                      onChanged: (value) {
                        setState(() {
                          dotFlashDisplayDuration = value.toInt();
                        });
                      },
                    ),
                    Text('$dotFlashDisplayDuration 秒',
                        style: TextStyle(color: Colors.grey[600])),
                    SizedBox(height: 16),
                    Text('圆点数量范围', style: TextStyle(fontSize: 16)),
                    SizedBox(height: 8),
                    Row(
                      children: [
                        Expanded(
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children:
                            [
                              Text('最小总圆点数: \$dotFlashMinDots 个', style: TextStyle(color: Colors.grey[600])),
                              Slider(
                                value: dotFlashMinDots.toDouble(),
                                min: 3,
                                max: 15,
                                divisions: 12,
                                label: dotFlashMinDots.toString(),
                                onChanged: (value) {
                                  setState(() {
                                    dotFlashMinDots = value.toInt();
                                    if (dotFlashMinDots > dotFlashMaxDots) {
                                      dotFlashMaxDots = dotFlashMinDots;
                                    }
                                  });
                                },
                              ),
                            ],
                          ),
                        ),
                        SizedBox(width: 16),
                        Expanded(
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children:
                            [
                              Text('最大总圆点数: \$dotFlashMaxDots 个', style: TextStyle(color: Colors.grey[600])),
                              Slider(
                                value: dotFlashMaxDots.toDouble(),
                                min: 3,
                                max: 15,
                                divisions: 12,
                                label: dotFlashMaxDots.toString(),
                                onChanged: (value) {
                                  setState(() {
                                    dotFlashMaxDots = value.toInt();
                                    if (dotFlashMaxDots < dotFlashMinDots) {
                                      dotFlashMinDots = dotFlashMaxDots;
                                    }
                                  });
                                },
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
              SizedBox(height: 32),
              Center(
                child: ElevatedButton.icon(
                  onPressed: _saveSettings,
                  icon: Icon(Icons.save),
                  label: Text('保存设置', style: TextStyle(fontSize: 18)),
                  style: ElevatedButton.styleFrom(
                    padding: EdgeInsets.symmetric(
                        horizontal: ResponsiveUtil.width(32), 
                        vertical: ResponsiveUtil.height(16)),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(12),
                    ),
                    minimumSize: Size(
                        ResponsiveUtil.width(30),
                        ResponsiveUtil.height(5)),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildSectionTitle(String title) {
    return Padding(
      padding: EdgeInsets.only(bottom: 8),
      child: Text(
        title,
        style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
      ),
    );
  }

  Widget _buildSettingCard({required Widget child}) {
    return Card(
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
      elevation: 4,
      child: Padding(
        padding: EdgeInsets.all(16),
        child: child,
      ),
    );
  }
}
